package com.lt.system;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellIdentityCdma;
import android.telephony.CellIdentityGsm;
import android.telephony.CellIdentityLte;
import android.telephony.CellIdentityWcdma;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.CellSignalStrengthCdma;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.TelephonyManager;

import com.lt.bean.LacStationInfo;
import com.lt.common.DebugHelper;

import java.util.ArrayList;
import java.util.List;


/**
 *
 */
public class LocationHelper {

    private Context mContext;
    private LocationCallBack mLocationCallBack;
    private LocationManager mManager;
    private String mProvider; //GPS定位方式

    public interface LocationCallBack {
        void onLocationChange(String provider, Location location);

        void onError(String err);
    }

    public LocationHelper(Context ctx) {
        this.mContext = ctx;
    }

    private void initLocationManager() {
        if (mManager == null) {
            mManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        }
    }

    //获取基站信息
    @SuppressLint("MissingPermission")
    public List<LacStationInfo> getTowerInfo() {
        int mcc = -1;
        int mnc = -1;
        int lac = -1;
        int cellId = -1;
        int rssi = -1;
        List<LacStationInfo> list = new ArrayList<>();
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return list;
        }
        String operator = tm.getNetworkOperator();
        if (operator != null && operator.length() > 4) {
            mcc = Integer.parseInt(operator.substring(0, 3));
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return list;
        }
        List<CellInfo> infos = null;
        try {
            infos = tm.getAllCellInfo();
        } catch (SecurityException e) {
            e.printStackTrace();
            return list;
        }

        if (infos == null || infos.size() == 0) {
            return list;
        }
        for (CellInfo info : infos) {
            if (info instanceof CellInfoCdma) {
                CellInfoCdma cellInfoCdma = (CellInfoCdma) info;
                CellIdentityCdma cellIdentityCdma = cellInfoCdma.getCellIdentity();
                mnc = cellIdentityCdma.getSystemId();
                lac = cellIdentityCdma.getNetworkId();
                cellId = cellIdentityCdma.getBasestationId();
                CellSignalStrengthCdma cellSignalStrengthCdma = cellInfoCdma.getCellSignalStrength();
                rssi = cellSignalStrengthCdma.getCdmaDbm();
            } else if (info instanceof CellInfoGsm) {
                CellInfoGsm cellInfoGsm = (CellInfoGsm) info;
                CellIdentityGsm cellIdentityGsm = cellInfoGsm.getCellIdentity();
                mnc = cellIdentityGsm.getMnc();
                lac = cellIdentityGsm.getLac();
                cellId = cellIdentityGsm.getCid();
                CellSignalStrengthGsm cellSignalStrengthGsm = cellInfoGsm.getCellSignalStrength();
                rssi = cellSignalStrengthGsm.getDbm();
            } else if (info instanceof CellInfoLte) {
                CellInfoLte cellInfoLte = (CellInfoLte) info;
                CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
                mnc = cellIdentityLte.getMnc();
                lac = cellIdentityLte.getTac();
                cellId = cellIdentityLte.getCi();
                CellSignalStrengthLte cellSignalStrengthLte = cellInfoLte.getCellSignalStrength();
                rssi = cellSignalStrengthLte.getDbm();
            } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1 && info instanceof CellInfoWcdma) {
                CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) info;
                CellIdentityWcdma cellIdentityWcdma = null;
                CellSignalStrengthWcdma cellSignalStrengthWcdma = null;
                cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
                mnc = cellIdentityWcdma.getMnc();
                lac = cellIdentityWcdma.getLac();
                cellId = cellIdentityWcdma.getCid();
                cellSignalStrengthWcdma = cellInfoWcdma.getCellSignalStrength();
                rssi = cellSignalStrengthWcdma.getDbm();
            } else {
                DebugHelper.e("get CellInfo error");
                return null;
            }
//            String tower = String.valueOf(mcc) + "#" + String.valueOf(mnc) + "#" + String.valueOf(lac)
//                    + "#CID:" + String.valueOf(cellId) + "#" + String.valueOf(rssi);
            list.add(LacStationInfo.getInfo(lac, cellId));
        }
        if (list.size() > 6) {
            list = list.subList(0, 5);
        }
//        else if (list.size() < 3) {
//            int need = 3 - list.size();
//            for (int i = 0; i < need; i++) {
//                list.add(LacStationInfo.getInfo(0, 0));
//            }
//        }
        return list;
    }

    public boolean hasGPSDevice() {
        initLocationManager();
        if (mManager == null)
            return false;
        final List<String> providers = mManager.getAllProviders();
        if (providers == null || providers.isEmpty())
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }


    //获取当前位置信息
    @SuppressLint("MissingPermission")
    public void addLocationListener(LocationCallBack listener) {
        this.mLocationCallBack = listener;
        initLocationManager();
        if (mManager == null) {
            setLocation(null);
            return;
        }
        String provider = null;
        //获取当前可用的位置控制器
        List<String> list = mManager.getProviders(true);
        if (list.contains(LocationManager.GPS_PROVIDER)) {
//            GPS位置控制器
            provider = LocationManager.GPS_PROVIDER;//GPS定位
            DebugHelper.e("GPS位置控制器");
        } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
//            网络位置控制器
            DebugHelper.e("网络位置控制器");
            provider = LocationManager.NETWORK_PROVIDER;//网络定位
        }
        if (mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            try {
                Location location = mManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    setLocation(location);
                    return;
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
        try {
            mManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
            Location location = mManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            setLocation(location);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    //获取当前位置信息
    public void addLocationListenerV2(LocationCallBack listener) {
        this.mLocationCallBack = listener;
        startLocation();
    }

    @SuppressLint("MissingPermission")
    private void startLocation() {
        initLocationManager();
        if (mManager == null) {
            setError("获取定位服务失败");
            return;
        }
        //获取当前可用的位置控制器
        List<String> list = mManager.getProviders(true);
        if (list.contains(LocationManager.GPS_PROVIDER)) {
//            GPS位置控制器
            mProvider = LocationManager.GPS_PROVIDER;//GPS定位
            DebugHelper.e("GPS位置控制器");
        } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
//            网络位置控制器
            DebugHelper.e("网络位置控制器");
            mProvider = LocationManager.NETWORK_PROVIDER;//网络定位
        }
        if (mProvider == null) {
            setError("没有可用的GPS控制器");
            return;
        }
        try {
//            if (Build.VERSION.SDK_INT >= 24) {
//                mManager.registerGnssStatusCallback(new GnssStatus.Callback() {
//                    @Override
//                    public void onStarted() {
//                        super.onStarted();
//                    }
//
//                    @Override
//                    public void onStopped() {
//                        super.onStopped();
//                    }
//
//                    @Override
//                    public void onFirstFix(int ttffMillis) {
//                        super.onFirstFix(ttffMillis);
//                    }
//
//                    @Override
//                    public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
//                        super.onSatelliteStatusChanged(status);
//                    }
//                });
//            }
            mManager.requestLocationUpdates(mProvider, 1000, 0, mLocationListener);
            Location location = mManager.getLastKnownLocation(mProvider);
            if (location == null) {
                location = mManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                setLocation(location);
            } else {
                setLocation(location);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
            setError("启动服务出现异常");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            setError("启动服务出现异常");
        } catch (RuntimeException e) {
            e.printStackTrace();
            setError("启动服务出现异常");
        }
    }

    @SuppressLint("MissingPermission")
    public void removeLocationListener() {
        if (mManager != null && mProvider != null) {
            try {
                mManager.removeUpdates(mLocationListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setLocation(Location l) {
        if (mLocationCallBack != null) {
            mLocationCallBack.onLocationChange(mProvider, l);
        }
    }

    private void setError(String err) {
        if (mLocationCallBack != null) {
            mLocationCallBack.onError(err);
        }
    }

    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            DebugHelper.e("onLocationChanged");
            setLocation(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {
            DebugHelper.e("onProviderEnabled:" + s);
            startLocation();
        }

        @Override
        public void onProviderDisabled(String s) {
            DebugHelper.e("onProviderDisabled:" + s);
            startLocation();
        }
    };


    //添加监听卫星
    private final GpsStatus.Listener mGpsStatusListener = new GpsStatus.Listener() {

        @Override
        public void onGpsStatusChanged(int event) {
            // TODO Auto-generated method stub
            //获取GPS卫星信息，与获取location位置信息一样，还是通过locationManager类，方法为getGpsStatus，返回的是一个GpsStatus类型的结构
//            gpsStatus = mManager.getGpsStatus(null);
            //触发事件event
            switch (event) {
                case GpsStatus.GPS_EVENT_STARTED:
                    break;
                //第一次定位时间
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    break;
                //收到卫星信息，并调用DrawMap()函数，进行卫星信号解析并显示到屏幕上
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    break;

                case GpsStatus.GPS_EVENT_STOPPED:
                    break;
            }
        }

        ;

    };

}
